var form = layui.form,
    upload = layui.upload,
    laydate=layui.laydate,
    table = layui.table,
    $ = layui.jquery,
    costCode = getQueryVariable("costCode");

$('#editor-form').find('input,textarea,select').attr('disabled',true);
//表单初始值
if (costCode != "") {
    form.val("editor-form", {
        "receiptnumber": "初始值",
    })
}
let costDetailData=[];
let costPaymentData=[];
//制单公司编号
let billCompanyCode;
//制单公司银行名称
let billCompanyBankName=[];
//制单公司银行账号
let billCompanyBanAccount=[];
//附件
let annexList=[];
//临时id
let tpId;

let usdRate;
let currencyName;
let currencyCode;
let rmbRate;
let thisUser;
//总金额
let totalAmount;
let bankNames;
let bankAccounts;

//实付金额
let countSum=0;

layer.ready(function () {
    //生成临时id
    tpId=Number(Math.random().toString().substr(3,3) + Date.now()).toString(36)
    //获取详情信息
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:costCode,
        async:false,
        url:"cost/getCostDetailByCostCode",
        success:function(res){
            if(res.status == 200){
                console.log(costCode)
                //主表信息赋值
                $("#code").val(res.data.code);
                if (res.data.costType==2){
                    $("#costType").val('间接费用');
                }else{
                    $("#costType").val('直接费用');
                }
                $("#currencyName").val(res.data.currencyName);
                $("#currencyCode").val(res.data.currencyCode);
                $("#rmbRate").val(res.data.rmbRate);
                $("#usdRate").val(res.data.usdRate);
                currencyName=res.data.currencyName;
                currencyCode=res.data.currencyCode;
                rmbRate=res.data.rmbRate;
                usdRate=res.data.usdRate;
                $("#payeeName").val(res.data.payeeName);
                $("#payeeCode").val(res.data.payeeCode);
                $("#bankName").val(res.data.bankName);
                bankNames=res.data.bankName
                $("#bankAccount").val(res.data.bankAccount);
                bankAccounts=res.data.bankAccount
                $("#totalAmount").val(res.data.totalAmount);
                totalAmount=res.data.totalAmount;
                $("#createTime").val(res.data.createTime);
                //收款单位编号
                billCompanyCode=res.data.billCompanyCode;
                $("#billCompanyCode").val(res.data.billCompanyCode);
                $("#billCompanyName").val(res.data.billCompanyName);
                $("#operatorCode").val(res.data.operatorCode);
                $("#operatorName").val(res.data.operatorName);
                $("#description").val(res.data.description);

                //费用明细列表信息
                costDetailData = res.data.costDetailVOList;
                //附件列表信息
                annexList = res.data.costAnnexVOList;
                //费用付款明细列表信息
                costPaymentData = res.data.costPaymentList;
                //添加临时id
                for(let i in costPaymentData){
                    costPaymentData[i].tId = tpId + (i+1);
                }


                table.reload('attachmenttableid',{data : annexList});
                table.reload('maininformationtableid',{data : costDetailData});
                table.reload('realpaysubsidiarytableid',{data : costPaymentData});

                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
    //根据制单公司编号获取银行名称集合
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:billCompanyCode,
        async:false,
        url:"costPayment/getBankDetailByBillCompanyCode",
        success:function(res){
            if(res.status == 200){
                for (let i in res.data) {
                    billCompanyBankName.push(res.data[i].bankName);
                }
            }
        }
    });

    //获取当前登录用户
    $.ajax({
        url:"costPayment/getThisUser",
        async:false,
        success:function(res){
            if(res.status == 200){
                thisUser=res.data;
            }
        }
    });

})

//监听提交
form.on('submit(form-element)', function (data) {
    var indexsl = 0;
    var maininformationdata = table.cache["realpaysubsidiarytableid"];
    $.each(maininformationdata,function(index,value){
        if(typeof (maininformationdata[index]["createTime"])== "undefined" || maininformationdata[index]["createTime"]==""){
            layer.msg("费用实付表第"+(index+1)+"条实付日期不能为空");
            indexsl++;
            return false;
        }else
            if(typeof (maininformationdata[index]["bankName"])== "undefined" || maininformationdata[index]["bankName"]==""){
            layer.msg("费用实付表第"+(index+1)+"条付款银行不能为空");
            indexsl++;
            return false;
        }else if(typeof (maininformationdata[index]["bankAccount"])== "undefined" || maininformationdata[index]["bankAccount"]==""){
            layer.msg("费用实付表第"+(index+1)+"条付款账号不能为空");
            indexsl++;
            return false;
        }else if(typeof (maininformationdata[index]["totalCost"])== "undefined" || maininformationdata[index]["totalCost"]=="" || maininformationdata[index]["totalCost"]==0){
            layer.msg("费用实付表第"+(index+1)+"条实付金额不能为空");
            indexsl++;
            return false;
        }
    });
    if(countSum>totalAmount) {
        layer.msg("实付金额总计不能大于总金额");
        indexsl++;
        return false;
    }
    if(indexsl == 0){

        for (let i in maininformationdata) {
            maininformationdata[i]['costCode']=costCode;
        }
        let datas=data.field;
        datas['costPaymentReqList']=maininformationdata;
        datas["annexReqs"] = table.cache["attachmenttableid"];
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:JSON.stringify(datas),
            url:"costPayment/addCostPaymentDetail",
            success:function (res) {
                if(res.status==200){
                    layer.msg("保存成功", {icon: 6});
                    parent.table.reload('maininformationtableid');
                    setTimeout(function () {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    },1000);
                    return false;
                }

            }
        });
    }

});

    table.render({
        elem: '#maininformation',
        id: 'maininformationtableid',
        data: costDetailData,
        cols: [[
            {field:'invoiceCode', title:'发票号码',sort:true},
            {field: 'increaseCode',  title: '增票号',sort:true},
            {field: 'contractNo',title: '外销合同号',sort:true},
            {field:'stockNoStr', title:'采购合同号',sort:true},
            {field: 'feeName',  title: '费用名称', sort:true},
            {field: 'applicationAmount',  title: '申请金额', sort:true},
            {field: 'salesmanName',  title: '承担人员',sort:true},
            {field:'accountantName', title:'核算人员', sort:true},
            {field:'departmentName', title:'核算部门', sort:true},
            {field: 'specialDesc',  title: '特殊备注',sort:true},
            {field: 'costClassification',  title: '费用归类',sort:true},
        ]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
    });


table.render({
    elem: '#realpaysubsidiary'
    ,data:costPaymentData
    ,toolbar:"#realpaysubsidiarytoolbar"
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field:'createTime',width:'150', title:'实付日期',sort:true,edit: true,event: 'realpaydate'}
        ,{field:'bankName',width:'200', title:'付款银行',templet: '#bankNameSelect'}
        ,{field:'bankAccount',width:'200', title:'付款账号',templet: '#bankAccountSelect'}
        ,{field:'currencyName',width:'80', title:'币种'}
        ,{field:'rmbRate',width:'100', title:'人民币汇率'}
        ,{field:'usdRate',width:'100', title:'美金汇率'}
        ,{field:'totalCost',width:'100', title:'实付金额',edit: 'text'}
        ,{field:'remark',width:'250', title:'实付备注',edit: 'text'}
        ,{field:'operatorName',width:'150', title:'操作员名称'}
    ]],
    done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
        $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
        // 当前表格渲染之后的视图
        let tableView = this.elem.next();

        for(let i in billCompanyBankName){
            $(".bankName").append("<option value=\"" + billCompanyBankName[i]+ "\">" + billCompanyBankName[i] + "</option>");
        }
        for (var i = 0; i < res.data.length; i++) {
            let bAcc;
            let tId = res.data[i].tId;
            $("#bankName_"+tId).val(res.data[i].bankName);
            let bName=res.data[i].bankName;
            $.ajax({
                type:"POST",
                data:{bankName:bName,billCompanyCode:billCompanyCode},
                async:false,
                url:"costPayment/getBankAccountByBankName",
                success:function(resR){
                    for(let i in resR.data.bankAccount){
                        $("#bankAccount_" + tId).append("<option value=\"" + resR.data.bankAccount[i]+ "\">" + resR.data.bankAccount[i] + "</option>");
                    }
                    bAcc=resR.data.bankAccount;
                    form.render('select');
                }
            });
            for (let j in bAcc) {
                if (bAcc[j]==res.data[i].bankAccount){
                    $("#bankAccount_" + tId).val(bAcc[j]);
                }
                if (isEmpty(res.data[i].bankAccount)){
                    res.data[i].bankAccount=bAcc[0];
                    $("#bankAccount_" + tId).val(bAcc[0]);
                }
            }
        }
        form.render('select');


    },
    id: 'realpaysubsidiarytableid'
    ,height: 380
    ,page: false
    ,limit: Number.MAX_VALUE
});

form.on("select(bankNameSelect_filter)", function(data){
    let bankName;
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["realpaysubsidiarytableid"];
    let tempId = tabledata[dataindex].tId;
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["bankName"] = data.value;
            bankName= data.value;
        }
    });
    $('#bankAccount_'+tabledata[dataindex].tId).empty();
    //根据银行名称获取银行账号集合
    $.ajax({
        type:"POST",
        data:{bankName:bankName,billCompanyCode:billCompanyCode},
        url:"costPayment/getBankAccountByBankName",
        success:function(res){
            for(let i in res.data.bankAccount){
                $("#bankAccount_" + tempId).append("<option value=\"" + res.data.bankAccount[i]+ "\">" + res.data.bankAccount[i] + "</option>");
            }
            if (res.data.bankAccount.length>0){
                $("#bankAccount_" + tempId).val(res.data.bankAccount[0]);
                tabledata[dataindex]['bankAccount']=res.data.bankAccount[0];
            }

            form.render('select');
        }
    });
});
form.on("select(bankAccountSelect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["realpaysubsidiarytableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["bankAccount"] = data.value;
        }
    });
});

form.on("select(currencyselect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["realpaysubsidiarytableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["currency"] = data.value;
        }
    });
});

table.on('edit(realpaysubsidiarytable)',function (obj) {
    let sum=new BigNumber(0);
    let amount;
    let totalAmountBig=new BigNumber(totalAmount);
    var old=$(this).prev().text();//旧值
    //判断数据类型 ,,,,,,,
    if(obj.field== "totalCost" && !isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        return;
    }
    var tabledata = table.cache["realpaysubsidiarytableid"];
    $.each(tabledata,function(index,value){
        if(value.totalCost==""){
            amount=new BigNumber(0).toFixed(2);
        }else {
            amount=new BigNumber(value.totalCost).toFixed(2);
        }
        sum=sum.plus(amount);
    });
    if (sum.comparedTo(totalAmount) == 1){
        countSum=sum.toFixed(2);
        layer.msg('实付金额总计不能大于总金额');
        return;
    }
    countSum=sum.toFixed(2);
    /*$.each(tabledata,function(index,value){
        let amountStr=value.totalCost;
        amount=Number(amountStr);
        if(isNaN(amount)){
            amount=0;
        }
        sum+=amount;
    });
    if (sum>totalAmount){
        countSum=sum;
        layer.msg('实付金额总计不能大于总金额');
        return;
    }
    countSum=sum;*/
});
//只有点击的时候才会进入这个里面
table.on('tool(realpaysubsidiarytable)',
    function (d) {
        var data = d.data;
        var newdata = {};
        if(!("id" in data)){
            switch (d.event) {
                case "realpaydate":
                    var field = $(this).data('field');
                    laydate.render({
                        elem: this.firstChild // 固定写
                        , show: true //直接显示
                        , closeStop: this
                        , type: 'date'
                        , format: "yyyy-MM-dd"
                        , done: function (value, date) {
                            newdata[field] = value;
                            d.update(newdata);
                            setTime(data, value);
                        }
                    });

                    break;
            }
        }
    });

function setTime(data, val){
    let tableData = table.cache["realpaysubsidiarytableid"];
    for(let i in tableData){
        if(data.tId == tableData[i].tId){
            tableData[i].createTime = val;
        }
    }
}
table.on('toolbar(realpaysubsidiarytable)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'new':
            var oldData = table.cache["realpaysubsidiarytableid"];
            let totalCostAll= $("#totalAmount").val();
            let oldTotalCost=0;
            for (let i = 0; i < oldData.length; i++) {
                let t=oldData[i].totalCost;
                if (isEmpty(t)){
                    t=0;
                }
                oldTotalCost = new BigNumber(oldTotalCost).plus(new BigNumber(t));
            }
            let totalCostNow = new BigNumber(totalCostAll).minus(oldTotalCost);
            if (totalCostNow.comparedTo(new BigNumber(0)) == -1) {
                totalCostNow = new BigNumber(0);
            }
           // var data1={"id":oldData.length+1};
            var data2={
                'tId':Number(Math.random().toString().substr(3,3) + Date.now()).toString(36),
                'usdRate':usdRate,
                'currencyName':currencyName,
                'currencyCode':currencyCode,
                'rmbRate':rmbRate,
                'operatorName':thisUser.name,
                'operatorCode':thisUser.code,
                "createTime" : currentDate,
                "totalCost" : totalCostNow.dp(4, BigNumber.ROUND_HALF_UP).toString(),
                "bankName":billCompanyBankName[0]
            };
            oldData.push(data2);
            table.reload('realpaysubsidiarytableid',{data : oldData});
            break;
        case 'del':
            var data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
                delList.push(n.tId);
            });
            if(delList!=''){
                layer.confirm('确定删除所选项吗？',function (index) {
                    let cbList = table.cache["realpaysubsidiarytableid"];
                    let allAccount=0;
                    for(let i = 0;i<cbList.length;i++) {
                        allAccount += Number(cbList[i].totalCost);
                    }
                    for(let i = 0;i<cbList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined"&&item == cbList[i].tId) {
                                let account=Number(cbList[i].totalCost);
                                allAccount=allAccount-account;
                                countSum=allAccount;
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("realpaysubsidiarytableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});

//---附件
table.render({
    elem: '#attachment'
    , data: annexList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
    , done: function (res, index, upload) {
        let data = res.data;
        for(let i in data){
            let flag = true;
            for(let j in annexList){
                if(data[i].id == annexList[j].id){
                    flag = false;
                    break;
                }
            }
            if(flag){
                annexList.push(data[i]);
            }
        }
    }
});
upload.render({
    elem: '#uploadfile'
    , url: 'transfer/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                annexList.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                }
            });
            break;
    };
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?',
            confirmInfo(3,5), function (index) {
                obj.del();
                let id = data.id;
                for (var i = 0; i < annexList.length; i++) {
                    if (annexList[i].id == id) {
                        annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                        i--; // 如果不减，将漏掉一个元素
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
                table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
            });
    }
});
//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}
let data2=[];
//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: data2
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}

//时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
function getNowFormatDate(type) {
    let date = new Date();
    let separator = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if(1 == type){
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }else if(2 == type){
        let second = date.getMilliseconds().toString();
        if(second.length < 3){
            if(second.length == 1){
                second = "0" + "0" + second;
            }else {
                second = "0" + second;
            }
        }
        let currentDate = year.toString() + month.toString() + strDate.toString() + second;
        return currentDate;
    }

}
function isEmpty(val) {
    if(val == "" || val == null || val == undefined){
        return true;
    }else {
        return false;
    }
}
let currentDate = getNowFormatDate(1);